package com.lzx.iteam;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.adapter.SecretaryAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.EventListData;
import com.lzx.iteam.bean.ScheduleData;
import com.lzx.iteam.bean.SecretaryBean;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.net.SystemListMsg;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.provider.ScheduleDB;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.DateUtil;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 05月 13日
 * Time: 下午4:53
 *
 * @QQ : 1234567890
 * **********************************
 */
public class SecretaryActivity extends MyBaseActivity implements View.OnClickListener, AbsListView.OnScrollListener, AdapterView.OnItemClickListener {

    private static String TAG = "SecretaryActivity";
    @FindViewById(id = R.id.lv_secretary)
    private ListView mListView;
    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvCenter;
    private TextView mHeaderText;
    private LinearLayout mHeaderLayout;
    private ProgressBar mHeaderProgress;

    private SecretaryAdapter mAdapter;
    private ArrayList<SecretaryBean> mListData = new ArrayList<SecretaryBean>();
    private ArrayList<SecretaryBean> mOldData = new ArrayList<SecretaryBean>();
    private ArrayList<SecretaryBean> mNewData = new ArrayList<SecretaryBean>();
    private int mPageIndex = 1;
    private CloudDBOperation mCloudDBOperation;
    private ScheduleDB mScheduleDb;
    private String mUid;


    private static final int GET_SYSTEM_LIST = 10001;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_SYSTEM_LIST:
                    if (msg.arg1 == 0) {
                        mNewData.clear();
                        mNewData = (ArrayList<SecretaryBean>) msg.obj;
                        if (mNewData.size() > 0) {
                            mOldData.clear();
                            mOldData.addAll(mListData);

                            mListData.clear();
                            mListData.addAll(mNewData);
                            mListData.addAll(mOldData);

                            mAdapter.bindData(mListData);
                            mListView.setSelectionFromTop(mNewData.size() + 1, Constants.dip2px(mActivity, 33));
                            if (mNewData.size() < 10) {
                                // TODO 如果第一页都没有10条，删除header
                                if (mPageIndex == 1) {
                                    mListView.removeHeaderView(mHeaderLayout);
                                }
                                mHeaderLayout.setVisibility(View.VISIBLE);
                                mHeaderProgress.setVisibility(View.GONE);
                                mHeaderText.setText("没有更多数据");
                            }
                        } else {
                            mHeaderProgress.setVisibility(View.GONE);
                            mHeaderText.setText("没有更多数据");
                        }
                    }
                    break;
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.secretary_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mListView.setOnScrollListener(this);
        mListView.setOnItemClickListener(this);
    }

    @Override
    public void initData() {
        mTvCenter.setText("小秘书");

        View headerView = LayoutInflater.from(this).inflate(R.layout.xlistview_footer, null);
        mHeaderLayout = (LinearLayout) headerView.findViewById(R.id.xlistview_footer_content);
        mHeaderText = (TextView) headerView.findViewById(R.id.xlistview_footer_hint_textview);
        mHeaderProgress = (ProgressBar) headerView.findViewById(R.id.xlistview_footer_progressbar);
        mHeaderLayout.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT,
                Constants.dip2px(mActivity, 30)));
        mHeaderLayout.setVisibility(View.GONE);
        mListView.addHeaderView(mHeaderLayout, null, false);

        mAdapter = new SecretaryAdapter(mActivity);
        mListView.setAdapter(mAdapter);
        getSystemMsgData();
        mCloudDBOperation = new CloudDBOperation(mActivity);
        mScheduleDb = new ScheduleDB(mActivity);
        mUid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_ll_back:
                finish();
                break;

        }
    }

    /**
     * 获取系统通知
     */
    public void getSystemMsgData() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, "10"));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, mPageIndex + ""));
        SystemListMsg messageMsg = new SystemListMsg(mHandler.obtainMessage(GET_SYSTEM_LIST), this);
        messageMsg.mApi = AsynHttpClient.API_SYSTEM_LIST;
        messageMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execCcHttp(messageMsg);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (view.getId()) {
            case R.id.lv_secretary:
                if (AbsListView.OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
                    // TODO 判断滚动到顶部
                    if (mListView.getFirstVisiblePosition() == 0) {
                        int counts = mPreferenceUtil.getInt("secretary_count", 1);
                        if (mAdapter.getCount() < counts) {
                            Log.d(TAG, "counts == " + counts + "   adapter == " + mAdapter.getCount());
                            mHeaderLayout.setVisibility(View.VISIBLE);
                            mPageIndex += 1;
                            getSystemMsgData();
                        } else if (mAdapter.getCount() == counts) {
                            mHeaderLayout.setVisibility(View.VISIBLE);
                            mHeaderProgress.setVisibility(View.GONE);
                            mHeaderText.setText("没有更多数据");
                        } else {
                            mHeaderProgress.setVisibility(View.GONE);
                            mHeaderText.setText("没有更多数据");
//                            mHeaderLayout.setVisibility(View.GONE);
                        }

                    }
                }
                break;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        SecretaryBean secretaryBean = null;
        // TODO 判断ListView 有没有header
        if (mListView.getHeaderViewsCount() == 0) {
            secretaryBean = mListData.get(position);
        } else {
            secretaryBean = mListData.get(position - 1);
        }
        /**
         * type
         * 01、审批    _id
         * 02、（木有）
         * 03、事件    event_id
         * 04、日程    event_id
         * 05、周报    weekly_id
         */
        String type = secretaryBean.getPush_type();
        String extra = secretaryBean.getExtra();
        if ("01".equals(type)) {
            try {
                JSONObject approval = new JSONObject(extra);
                String approvalId = approval.getString("_id");
                Intent app = new Intent(mActivity, ApprovalDetailActivity.class);
                app.putExtra("approval_id", approvalId);
                startActivity(app);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if ("02".equals(type)) {

        } else if ("03".equals(type)) {
            try {
                JSONObject event = new JSONObject(extra);
                String eventId = event.getString("event_id");
                EventListData eventData = mCloudDBOperation.findOneEventById(eventId);
                if (StringUtil.isEmpty(eventData.getEventId())) {
                    showShortToast("该事件已删除");
                } else {
                    Intent eventDetail = new Intent(mActivity, EventDetailContentActivity.class);
                    eventDetail.putExtra("event_msg", eventData);
                    startActivity(eventDetail);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if ("04".equals(type)) {
            try {
                JSONObject schedule = new JSONObject(extra);
                Long time = Long.parseLong(schedule.getString("start_datetime")) * 1000;
                String date = DateUtil.getScheduleTime(time);
                String eventId = schedule.getString("event_id");
                ScheduleData scheduleData = mScheduleDb.findScheduleById(date, mUid, eventId);
                Intent sche = new Intent(mActivity, ScheduleDetailActivity.class);
                if (StringUtil.isEmpty(scheduleData.getId())) {
                    if (schedule.has("hidden")) {
                        scheduleData.setHidden(schedule.getString("hidden"));
                    } else {
                        scheduleData.setHidden("0");
                    }
                    scheduleData.setId(schedule.getString("event_id"));
                    scheduleData.setStartTime(schedule.getString("start_datetime"));
                    scheduleData.setTitle(schedule.getString("event_title"));
                    scheduleData.setPublishedUName(schedule.getString("delegater_username"));
                    scheduleData.setAlertTime(schedule.getString("alert_datetime"));
                    if (schedule.has("done")) {
                        scheduleData.setDone(schedule.getString("done"));
                    } else {
                        scheduleData.setDone("0");
                    }
                    scheduleData.setRemark(schedule.getString("remark"));
                    scheduleData.setNotice(schedule.getString("update"));
                    scheduleData.setUpdateTime(schedule.getString("update_time"));
                    scheduleData.setCreateTime(schedule.getString("create_time"));
                    scheduleData.setPublishedUId(schedule.getString("delegate_user"));
                    scheduleData.setEndTime(schedule.getString("end_datetime"));
                    scheduleData.setAddress(schedule.getString("address"));
                    scheduleData.setHasRead(schedule.getString("has_read"));
                    scheduleData.setBossUid(schedule.getString("user_id"));
                    mScheduleDb.addSchedule("1", date, scheduleData);
                }
                sche.putExtra("scheduleData", scheduleData);
                sche.putExtra("isMe", true);
                startActivity(sche);


            } catch (JSONException e) {
                e.printStackTrace();
            }

        } else if ("05".equals(type)) {
            try {
                JSONObject weeklyData = new JSONObject(extra);
                Intent weekly = new Intent(SecretaryActivity.this, WeeklyDetailActivity.class);
                weekly.putExtra("weeklyId", weeklyData.getString("weekly_id"));
                weekly.putExtra("groupId", weeklyData.getString("group_id"));
                startActivity(weekly);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }
}
